package util;

import entity.ResponseMessage;
import entity.StatusCode;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * The type File upload.
 */
public class FileUpload {
    /**
     * File upload response message.
     *
     * @param mul the mul
     * @return the response message
     */
    public static ResponseMessage fileUpload(MultipartFile mul) {
        ResponseMessage msg = new ResponseMessage();

        String path = "D://finally/picture";
        File file = new File(path);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
        }
        String originalFilename = mul.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        String uuidString = UUID.randomUUID().toString();
        String fileName = uuidString + "." + extension;

        File fileUpload = new File(file, fileName);
        try {
            mul.transferTo(fileUpload);
//            CompressImg.compress(fileName);
            msg.setFlag(true);
            msg.setCode(StatusCode.OK);
            msg.setData(fileName);
        } catch (IOException e) {
            msg.setCode(StatusCode.ERROR);
            msg.setFlag(false);
            e.printStackTrace();
            return msg;
        }

        return msg;
    }
}
